package com.aivin.lib_base.tool;

import com.aivin.lib_base.bean.HeartBeatTask;

import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 优点除了线程池的特性以外，可以实现循环或延迟任务
 */

public class WkHeartBeatTool {
    private ScheduledExecutorService mScheduledExecutorService;
    private HashMap<String, Future> map  ;

    public WkHeartBeatTool() {
        initTool();
    }

    /**
     * 获取 任务总数
     */
    public int getTaskNum(){
        return map==null? 0 : map.size() ;
    }


    /**
     * 初始化
     */
    private void initTool() {
        /// 线程池大小  5
        mScheduledExecutorService = Executors.newScheduledThreadPool(5);
        map = new HashMap<String, Future>() ;

    }

    /**
     *  开始一个心跳 任务. TimeUnit.MILLISECONDS ,
     */
    public void startTheBeatAction(HeartBeatTask task , int period){
        if(map.containsKey(task.getTaskName())){
            /// System.out.println("心跳正在进行，无需重复添加");
            return ;
        }
        Future future = mScheduledExecutorService.scheduleAtFixedRate( task , 0, period, TimeUnit.MILLISECONDS);
        map.put(task.getTaskName() , future) ;

    }


    /**
     * 关闭指定的心跳任务
     */
    public void shutDownTheBeatAction(HeartBeatTask task ){
        Future future = map.get(task.getTaskName()) ;
        // 传入true会中断线程停止任务
        if(future!=null){
            future.cancel(true) ;
            map.remove(task.getTaskName()) ;
        }else{
            System.out.println("你指定的这个心跳任务已经不存在，无需关闭");
        }
    }


    /**
     * 延时任务 , TimeUnit.MILLISECONDS
     */
    public void startDelayedAction( HeartBeatTask task , int delayTime){
        mScheduledExecutorService.schedule( task, delayTime , TimeUnit.MILLISECONDS );
    }


    /**
     * 销毁所有变量
     */
    public void shutDownAll() {
        if (mScheduledExecutorService != null) {
            // 强制关闭
            mScheduledExecutorService.shutdownNow();
            mScheduledExecutorService = null;
        }

        map.clear();
        map=null ;
    }

}
